import websocket    # 安装库 websocket-client，而不是websocket
import time
import json
'''
websocket在js中的逆向技巧：（实时流，用于金融，弹幕，直播）
    new webSocket()  ：固定写法，new一个对象
    webSocket.send   :用于向服务器发送请求
    webSocket.onopen :用于指定连接成功后的回调函数
    webSocket.onmessage : 用于指定收到服务器数据后的回调函数
    webSocket.onclose   : 用于指定连接关闭后的回调函数
    webSocket。binaryType = 'arraybuffer'  : 用来表示通用的，固定长度的二进制数据
'''
# python如何实现websocket
# 找到socket接口url
url = 'wss://score-p.599.com/scorepush/football'
headers = {
    "Upgrade": "websocket",
    "Origin": "https://www.599.com",
    "Cache-Control": "no-cache",
    "Accept-Language": "zh-CN,zh;q=0.9",
    "Pragma": "no-cache",
    "Connection": "Upgrade",
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36",
    "Sec-WebSocket-Version": "13",
    "Sec-WebSocket-Extensions": "permessage-deflate; client_max_window_bits",
    "cookie" : "douyin_ads=XhfWmQHvT2; Hm_lvt_b8167d9d4d6b87ad4f016f6096a48019=1753490796; HMACCOUNT=960263B4D96B0969; acw_tc=3a90fc9717534955322246144e94f034f4db49b151aa7268c043ca0f05; cdn_sec_tc=3a90fc9717534955322246144e94f034f4db49b151aa7268c043ca0f05; Hm_lpvt_b8167d9d4d6b87ad4f016f6096a48019=1753497616; ads-tracker-baidu=8vfdBO93APOsttncvi7yP5GdKZY7IoNs6unKeqQ1EGSRdkCQLyZ4c8UMMZGftjerPc9AkBn90cLwy3fR"
}
# 创建连接（跳过 SSL 验证）
ws = websocket.create_connection(
    url,
    header=headers,
    sslopt={"cert_reqs": False}  # 关键点：添加在这里
)

# 发送订阅消息
ws.send(json.dumps({"device": "pc", "topic": "USER.topic.app.8"}))

# 接收数据
try:
    while True:
        message = ws.recv()
        print(message)
        time.sleep(1)
except websocket.WebSocketException as e:
    print("Error:", e)
finally:
    ws.close()

